<?php
defined('IN_IA') or exit('Access Denied');
define('ROOT_PATH', str_replace('site.php', '', str_replace('\\', '/', __FILE__)));
define('INC_PATH',ROOT_PATH.'inc/');


class Dg_datiModuleSite extends WeModuleSite {	
	
	//调试
	  function __construct(){
	  	global $_GPC, $_W;
	  if ( strpos($_SERVER['HTTP_USER_AGENT'],'MicroMessenger') !== false ) {
	  	
	  	}else{
	  		$_W["openid"]='oU4go0msnyP2JizVuKdoNoZ1xLqo';
	  	}
	  }
	
	public function doWebManage() {
		global $_GPC, $_W;
		
		load()->model('reply');
		$pindex = max(1, intval($_GPC['page']));
		$psize = 20;
		$params = array();
		$acid=$_W['uniacid'];
		$total = pdo_fetchcolumn("SELECT count(id) FROM " . tablename('dt_question_reply') . " WHERE iacid=" . $acid);
		
		$sql = "select * from ".tablename("dt_question_reply")." where uniacid = :iacid";
		$params = array();
		$params[':iacid'] = $acid;

		$list = pdo_fetchall($sql,$params);
		$pager = pagination($total, $pindex, $psize);
		
		include $this->template ( 'manage' );
	}
	
	
	/**
	 * 核销管理
	 */
	public function doWebHexiaoManage(){
		global $_GPC, $_W;
		$rid=intval($_GPC["rid"]);
		if($rid==0){
			$rid=$_COOKIE["rid"];
		}
		$params = array();
		$acid=$_W['uniacid'];
	
		$list = pdo_fetchall("select hexiao.*,userinfo.nicename,userinfo.niceshop,userinfo.province,userinfo.name,userinfo.phone from ims_dt_hexiao hexiao 
				left join ims_dt_userinfo userinfo on userinfo.openid=hexiao.to_openid order by hexiao.id desc");
		
		setcookie("rid",$rid);
		include $this->template('hexiaomanage');
	}
	
	/**
	 * 答题管理
	 */
	public function doWebDatiManage(){
		global $_GPC, $_W;
		$rid=intval($_GPC["rid"]);
		if($rid==0){
			$rid=$_COOKIE["rid"];
		}
		$params = array();
		$acid=$_W['uniacid'];
		
		$list = pdo_fetchall("SELECT * FROM " . tablename('dt_question') . " WHERE rid = :rid order by id desc", array(':rid' => $rid));
		setcookie("rid",$rid);
		include $this->template('datimanage');
	}
	
	
	//核销管理 
	public function doWebAddManage(){
		global $_GPC, $_W;
		$rid=$_COOKIE["rid"];
		load()->func('tpl');
		$acid = empty($_W['acid']) ? $_W['uniacid'] : $_W['acid'];
		$id = intval($_GPC['id']);
		$question;
		if(!empty($id) && $id!=0){
			$question = pdo_fetch("SELECT * FROM " . tablename('dt_question') . " WHERE id = :id ", array(':id' => $id));
		}else{
			$question = array(
					"type" => "1",
			);
		}
		include $this->template('adddati');
	}
	
	/**
	 * 添加,编辑答题
	 */
	public function doWebAddDati(){
		global $_GPC, $_W;
		$rid=$_COOKIE["rid"];
		load()->func('tpl');
		$acid = empty($_W['acid']) ? $_W['uniacid'] : $_W['acid'];
		$id = intval($_GPC['id']);
		$question;
		if(!empty($id) && $id!=0){
			$question = pdo_fetch("SELECT * FROM " . tablename('dt_question') . " WHERE id = :id ", array(':id' => $id));
		}else{
			$question = array(
					"type" => "1",
			);
		}
		include $this->template('adddati');
	}
	
	public function doWebEditDati(){
		global $_GPC, $_W;
		$rid=intval($_GPC["rid"]);
		
		$acid=$_W['uniacid'];
		$id = intval($_GPC['id']);
		$insert;
		
		if($_GPC['type']==1){
			$insert = array(
					'rid' => $rid,
					'iacid'=>$acid,
					'uniacid' => $acid,
					'question' => $_GPC['question'],
					'quesimage'=>$_GPC['quesimage'],
					'realanswer' => $_GPC['realans'],
					'type' => $_GPC['type'],
					'points' => $_GPC['points'],
					'answerA'=> $_GPC['answerA'],
					'answerB'=> $_GPC['answerB'],
					'answerC'=> $_GPC['answerC'],
					'is_must'=> $_GPC['is_must'],
					//'answerD'=> $_GPC['answerD'],
			);
		}else{
			$insert = array(
					'rid' => $rid,
					'iacid'=>$acid,
					'uniacid' => $acid,
					'question' => $_GPC['question'],
					'quesimage'=>$_GPC['quesimage'],
					'realanswer' => implode("",$_GPC['realanswer']),
					'type' => $_GPC['type'],
					'points' => $_GPC['points'],
					'answerA'=> $_GPC['answerA'],
					'answerB'=> $_GPC['answerB'],
					'answerC'=> $_GPC['answerC'],
					'is_must'=> $_GPC['is_must'],
				//	'answerD'=> $_GPC['answerD'],
			);
		}
		$ret;
		//先删除
		pdo_delete("dt_question", array('id' => $id));
		//再插入
		$ret = pdo_insert("dt_question", $insert);
		
		if (!empty($ret)) {
			message('操作成功！', $this->createWebUrl("datimanage",array("rid"=>$rid)), 'success');
		}else{
			message('操作失败！', referer(), 'error');
		}
	}
	
	public  function doWebDeleteDati(){
		global $_GPC, $_W;
		$rid=intval($_GPC["rid"]);
		$id=intval($_GPC["id"]);
		pdo_delete('dt_question', array('rid' => $rid,'id' => $id));
		message('删除成功！', referer(), 'success');
	}
	
	public  function doWebDeleteHexiao(){
		global $_GPC, $_W;
		//$rid=intval($_GPC["rid"]);
		$id=intval($_GPC["id"]);
		pdo_delete('dt_hexiao', array('id' => $id));
		message('删除成功！', referer(), 'success');
	}
	
	public  function doWebMustDati(){
		global $_GPC, $_W;
		$rid=intval($_GPC["rid"]);
		$id=intval($_GPC["id"]);
		pdo_update('dt_question', array('is_must'=>0),array('rid' => $rid));
		pdo_update('dt_question', array('is_must'=>1),array('rid' => $rid,'id' => $id));
		message('操作成功！', referer(), 'success');
	}
	
	
	/**
	 * 操作活动开始或者结束
	 */
	public function doWebHdControl(){
		global $_GPC, $_W;
	
		$status = $_GPC['status'];
		$rid=$_GPC["rid"];
	
		$data = array('status' => $status);
		$params = array('rid'=>$rid);
		$re=pdo_update('dt_question_reply',$data,$params);
		if(!empty($re)){
			message('操作成功！', referer(), 'success');
		}else{
			message('操作失败！', referer(), 'error');
		}
	}
	
	public function doWebDelete() {
		global $_GPC, $_W;
		$rid = intval($_GPC['rid']);
		// $rule = pdo_fetch("SELECT id, module FROM " . tablename('rule') . " WHERE id = :id and uniacid=:iacid", array(':id' => $rid, ':iacid' => $_W['uniacid']));
		// if (empty($rule)) {
			// message('抱歉，要修改的规则不存在或是已经被删除！');
		// }
		// if (pdo_delete('rule', array('id' => $rid))) {
			// pdo_delete('rule_keyword', array('rid' => $rid));
			////删除统计相关数据
			// pdo_delete('stat_rule', array('rid' => $rid));
			// pdo_delete('stat_keyword', array('rid' => $rid));
			////调用模块中的删除
			// $module = WeUtility::createModule($rule['module']);
			// if (method_exists($module, 'ruleDeleted')) {
				// $module->ruleDeleted($rid);
			// }
		// }
		pdo_delete('rule_keyword', array('rid' => $rid));
		pdo_delete('stat_rule', array('rid' => $rid));
		pdo_delete("dt_question_reply", array('rid' => $rid));
		
		message('操作成功！', referer(), 'success');
	}
	
	public function doWebDeleteAll() {
		global $_GPC, $_W;
		$idArr = $_GPC['ridArr'];
		for($i=0;$i<count($idArr);$i++){
			$id=$idArr[$i];
			pdo_delete("dt_question_reply", array('rid' => $id));
			pdo_delete('rule_keyword', array('rid' => $rid));
			pdo_delete('stat_rule', array('rid' => $rid));
		}
		$fmdata=array(
			"errno"	=>0
		);
		echo json_encode($fmdata);
	}
	//删除全部题目
	public function doWebDeletetiAll() {
		global $_GPC, $_W;
		$idArr = $_GPC['ridArr'];
		for($i=0;$i<count($idArr);$i++){
			$id=$idArr[$i];
			pdo_delete("dt_question", array('id' => $id));
		}
		$fmdata=array(
			"errno"	=>0
		);
		echo json_encode($fmdata);
	}
	/**
	 * 参与记录
	 */
	public function doWebRecord(){
		global $_GPC, $_W;
		load()->model('reply');
		load()->func('tpl');
		$rid=$_GPC["rid"];
		$acid=$_W['uniacid'];
		
		if($nick=$_POST['nick']){
			
		}
		//分页
		$pindex = max(1, intval($_GPC['page']));
		$psize = 100;
		$reply=pdo_fetch("SELECT * FROM " . tablename('dt_question_reply') . " WHERE rid = :rid ", array(':rid' => $rid));
		$iswanshan=$reply["iswanshan"];
		if($nick){
			$list=pdo_fetchall("SELECT openid,pointstime,nick,headimg,points,sytime,addtime,name,phone,addr
				from ims_dt_userinfo  where rid=$rid and nick like '%$nick%' and sytime>0 order by points desc,sytime asc ");
			
			$userlist=pdo_fetchall("SELECT openid,pointstime,id,rid,openid,nick,headimg,points,sytime,addtime,name,phone,addr
					from ims_dt_userinfo  where rid=$rid and nick like '%$nick%' and sytime>0 order by points desc,sytime asc LIMIT ".($pindex - 1) * $psize.",". $psize, array(':rid' => $rid));
		}else{
			$list=pdo_fetchall("SELECT openid,pointstime,nick,headimg,points,sytime,addtime,name,phone,addr
				from ims_dt_userinfo  where rid=$rid and sytime>0 order by points desc,sytime asc ");
			
			$userlist=pdo_fetchall("SELECT openid,pointstime,id,rid,openid,nick,headimg,points,sytime,addtime,name,phone,addr
					from ims_dt_userinfo  where rid=$rid  and sytime>0 order by points desc,sytime asc LIMIT ".($pindex - 1) * $psize.",". $psize, array(':rid' => $rid));
		}
		
		$total=count($list);
		
		
		foreach ($userlist as &$val){
			$openid=$val['openid'];
			$dtuser_points=pdo_fetch("SELECT sum(points) sum_points, count(*) count_points FROM ". tablename('dt_userpoints')." WHERE openid=:openid and rid=:rid
			and status=:status and points>0" , array(":openid"=>$openid,":rid"=>$rid,":status"=>1));
			
			$dtuser_points_counts=$dtuser_points['sum_points'];
			$dtuser_points_counts=$dtuser_points_counts ? $dtuser_points_counts :0;
			$val['dtuser_points_counts']=$dtuser_points_counts;
			
			$val['count_points']=$dtuser_points['count_points'];
		}
		$pager = pagination($total, $pindex, $psize);
		
		include $this->template("record");
	}
	/**
	 * 修改参与记录
	 */
	public function doWebEditRecord(){
		global $_GPC, $_W;
		load ()->func ( 'tpl' );
		$id=$_GPC["id"];
		$record=pdo_fetch("SELECT * FROM ". tablename('dt_userinfo')." WHERE id=:id", array(':id' => $id));
		
		include $this->template("editrecord");
	}
	public function doWebEditRecord2(){
		global $_GPC, $_W;
		$id=$_GPC["id"];
		$points=$_GPC["points"];
		$data = array(
				"points"=>$points
		);
		pdo_update('dt_userinfo', $data, array('id' => $id));
		$fmdata = array(
				"success" =>1,
				"msg" => "更新成功"
		);
		echo json_encode($fmdata);
	}
	/**
	 * 删除参与记录
	 */
	public function doWebdeleterecord(){
		
		global $_GPC, $_W;
		$rid = intval($_GPC['rid']);
		$id=$_GPC['id'];
		$openid=$_GPC['openid'];
		
		pdo_delete("dt_userinfo", array('openid'=>$openid,'rid' => $rid));//删除参与者数据
		message('操作成功！', referer(), 'success');
	}
	
	public function doWebdeleteallrecord(){
		global $_GPC, $_W;
		$rid = intval($_GPC['rid']);
		pdo_delete("dt_userinfo", array('rid' => $rid));
		message('操作成功！', referer(), 'success');
	}
	
	//导出数据
	public function doWebdownloadhexiao(){
		global $_GPC,$_W;
		$rid= intval($_GPC['rid']);
		$acid=$_W['uniacid'];
		if(empty($rid)){
			message('抱歉，传递的参数错误！','', 'error');
		}
	//	$reply = pdo_fetch("SELECT * FROM ".tablename('dt_question_reply')." WHERE rid = :rid", array(':rid' => $rid));
		
		$list = pdo_fetchall("select hexiao1.name,
				hexiao1.province,
				hexiao1.phone,
				hexiao1.nicename,
				hexiao1.niceshop,
				hexiao1.dtuser_points_counts,
				FROM_UNIXTIME(hexiao1.ctime) ctime,
				userinfo1.nick root_nick from (select hexiao.*,userinfo.nicename,userinfo.niceshop,userinfo.province,userinfo.name,userinfo.phone from ims_dt_hexiao hexiao 
				left join ims_dt_userinfo userinfo on userinfo.openid=hexiao.to_openid order by hexiao.id desc) hexiao1 left join ims_dt_userinfo userinfo1
on hexiao1.root_openid=userinfo1.openid
				");
		
		//print_r($list); die();
		
		$tableheader = array('id','用户名','省份', '手机号', '美容院','品牌' ,'核销金额','核销日期',"核销管理员");
		$html = "\xEF\xBB\xBF";
		foreach ($tableheader as $value) {
			$html .= $value . "\t ,";
		}
		$html .= "\n";
		foreach ($list as $mid => $value) {
			$p = $mid + 1;
			$html .= $p . "\t ,";
			$html .= $value['name'] . "\t ,";
			$html .= $value['province'] . "\t ,";
			$html .= $value['phone'] . "\t ,";
			$html .= $value['nicename'] . "\t ,";
			//$html .= date("Y-m-d H:i:s",$value['addtime']) . "\t ,";
			$html .= $value['niceshop'] . "\t ,";
			$html .= $value['dtuser_points_counts'] . "\t ,";
			$html .= $value['ctime'] . "\t ,";
			$html .= $value['root_nick'] . "\t ,";
			$html .= "\n";
		}
		//$filename = $reply['huodongname'].'_'.$rid;
		$filename='核销记录';
		header("Content-type:text/csv");
		header("Content-Disposition:attachment; filename=".$filename.".csv");
	
		echo $html;
		exit();
	}
	
	//导出数据
	public function doWebdownload(){
		global $_GPC,$_W;
		$rid= intval($_GPC['rid']);
		$acid=$_W['uniacid'];
		if(empty($rid)){
			message('抱歉，传递的参数错误！','', 'error');
		}
		$reply = pdo_fetch("SELECT * FROM ".tablename('dt_question_reply')." WHERE rid = :rid", array(':rid' => $rid));
		$userlist=pdo_fetchall("SELECT nick,headimg,points,sytime,addtime,name,phone,addr from".tablename('dt_userinfo')." where rid=:rid and nick<>'' and points<>'' order by points desc,sytime,addtime", array(':rid' => $rid));
		$tableheader = array('序号','昵称', '头像', '分数','用时' ,'参与时间','姓名',"手机号","备注");
		$html = "\xEF\xBB\xBF";
		foreach ($tableheader as $value) {
			$html .= $value . "\t ,";
		}
		$html .= "\n";
		foreach ($userlist as $mid => $value) {
			$p = $mid + 1;
			$html .= $p . "\t ,";
			$html .= $value['nick'] . "\t ,";
			$html .= $value['headimg'] . "\t ,";
			$html .= $value['points'] . "\t ,";
			$html .= $value['sytime'] . "\t ,";
			$html .= date("Y-m-d H:i:s",$value['addtime']) . "\t ,";
			$html .= $value['name'] . "\t ,";
			$html .= $value['phone'] . "\t ,";
			$html .= $value['addr'] . "\t ,";
			$html .= "\n";
		}
		$filename = $reply['huodongname'].'_'.$rid;
	
		header("Content-type:text/csv");
		header("Content-Disposition:attachment; filename=".$filename.".csv");
	
		echo $html;
		exit();
	}
	/**
	 * 同步用户信息
	 */
	public function doWebupgred(){
		global $_GPC,$_W;
		load()->model('mc');
		$rid= intval($_GPC['rid']);
		$acid=$_W['uniacid'];
		$psql="select * from ".tablename('dt_userinfo')." where rid=:rid";
		$plist=pdo_fetchall($psql,array(':rid' => $rid));
	
		for($i=0;$i<count($plist);$i++){
			if(empty($plist[$i]['nick']) || empty($plist[$i]['headimg'])){
				$fan=mc_fansinfo($plist[$i]["openid"],$acid,$acid);
				$para = array(
						'nick'=>$fan['nickname'],
						'headimg'=>$fan["tag"]['avatar']
				);
				pdo_update('dt_userinfo', $para, array('id' => $plist[$i]["id"]));
			}
		}
		message('操作成功！', referer(), 'success');
	}
	
	function is_weixin(){
	
		if ( strpos($_SERVER['HTTP_USER_AGENT'],
	
				'MicroMessenger') !== false ) {
	
				return true;
	
		}
	
		return false;
	
	}
	/**
	 * 获取用户信息
	 */
	public function getUserInfo($rid){
		global $_GPC,$_W;
		
		

		if($this->is_weixin()){
		
			if($_SERVER['SERVER_PORT']=='80'){
				$redirect_uri='http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
			}else{
				$redirect_uri='https://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
			}
			$cuser_info=$_GPC[$rid.'dg_user_info'];
			
			if(empty($cuser_info)){
				$oauth2=new Oauth2($_W['oauth_account']);
			
				if(empty($_GPC['code'])){
					$oauth2->authorization_code($redirect_uri, Oauth2::$SCOPE_USERINFO,'we7sid-'.$_W['session_id']);
				}
				$code=$_GPC['code'];
			
				$access_token=$oauth2->getOauthAccessToken($code);
			
				$user_info=$oauth2->getOauthUserInfo($access_token['openid'], $access_token['access_token']);
			
				$cookieKey=$rid."dg_user_info";
				$cuser_info=$oauth2::setClientCookieUserInfo($user_info,$cookieKey);
			}
			
			$user_info=base64_decode($cuser_info);
			return $user_info;
		}else{
		
			//调试
		$user_info=array('nickname'=>'让心灵去旅行',
				'headimgurl'=>'http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83erY5c9JicvJJGHJqZV17FdvGOsfwSUIZ3Mu8O0lgR1sibw1c7fibMl9fLBjhrZL7m3QMU6wUIqE5rwBA/132',
				'uid'=>62,
				'openid'=>'oU4go0msnyP2JizVuKdoNoZ1xLqo'
		);
		
		$cookie = array();
		$cookie['openid'] = $userInfo['openid'];
		$cookie['uid'] = $userInfo['uid'];
		$cookie['nickname'] = $userInfo['nickname'];
		$cookie['headimgurl'] = $userInfo['headimgurl'];
		//$cookie['headimgurl']=str_replace("/0","/132",$cookie['headimgurl']);
		$session = base64_encode(json_encode($cookie));
		isetcookie($cookieKey, $session, 48 * 3600 * 1);
		//return $session;
		
		return json_encode($user_info);
		}
		
		
		
		
	}
	
	/**
	 * 导入题库
	 */
	public function dowebimportdati(){
		global $_GPC, $_W;
		load()->func('tpl');
		$rid=$_GPC["rid"];
		include $this->template("import");
	}
	
	/**
	 * 核销
	 */
	public function domobilehexiao(){
		global $_GPC, $_W;
      // exit('aaaa');
		$id=$_GPC["id"];
		$rid=$_GPC["rid"];
		$hxnum=$_GPC["hxnum"];
		$to_openid=$_GPC['openid'];
		$openid = $_W["openid"];
		
		if($reply["subscribe"]==1){
			$nick=$_W['fans']['nickname'];
			$headimg=$_W['fans']['tag']['avatar'];
		}else{
			$userinfo=$this->getUserInfo($rid);
			$obj = json_decode($userinfo);
			$nick=$obj->nickname;
			$headimg=$obj->headimgurl;
		}
		
		$reply = pdo_fetch("SELECT * FROM " . tablename('dt_question_reply') . " WHERE rid = :rid ", array(':rid' => $rid));
		$root_openid=explode(",", $reply['root_openid']);
		$root_openid=array_filter($root_openid);
		
		$dtuser_points_counts=pdo_fetchcolumn("SELECT sum(points) FROM ". tablename('dt_userpoints')." WHERE openid=:openid and rid=:rid
			and status=:status " , array(":openid"=>$to_openid,":rid"=>$rid,":status"=>1));
		
		if(!$reply || $dtuser_points_counts<=0){
			exit("<h1>核销失败,无宝藏记录</h1>");
		}
		
		if(!in_array($openid,$root_openid)){
			exit("<h1>您没有权限核销用户</h1>");
		}
		
		$data['root_openid']=$openid;
		$data['to_openid']=$to_openid;
		$data['dtuser_points_counts']=$dtuser_points_counts;
		$data['ctime']=time();
	//print_r($data); die();
		pdo_insert("dt_hexiao",$data);
		$id=pdo_insertid();
		
		
		$res= pdo_query("update ims_dt_userpoints set status=0 where openid='$to_openid'");
		if($res){
			exit("<h1>核销成功数量$dtuser_points_counts</h1>");
		}else{
			exit("<h1>核销失败1</h1>");
		}
		
		
	
	}
	
	//完善信息
	public function domobileaddexchange(){
		global $_W,$_GPC;
		load()->func('tpl');
		$rid=$_GPC["rid"];
		$acid=$_W['uniacid'];
		$reply=pdo_fetch("SELECT * FROM " . tablename('dt_question_reply') . " WHERE rid = :rid ", array(':rid' => $rid));
		$zongfen=intval($reply["zongfen"]);
	
		$openid = $_W["openid"];
		if($reply["subscribe"]==1){
			$nick=$_W['fans']['nickname'];
			$headimg=$_W['fans']['tag']['avatar'];
		}else{
			$userinfo=$this->getUserInfo($rid);
			$obj = json_decode($userinfo);
			$nick=$obj->nickname;
			$headimg=$obj->headimgurl;
		}
	
	
		$fromid=$_GPC["fromid"];
		$points=intval($_GPC["totalpoints"])<=$zongfen?intval($_GPC["totalpoints"]):$zongfen;
		$stime=$_COOKIE["stime"];
		$sytime=time()-intval($stime);
		$questime=$reply["questiontime"];
		if(intval($sytime)>intval($questime)*60){
			$sytime=intval($questime)*60;
		}
		$time=date('Y-m-d H:i:s',time());
		$name=$_GPC["name"];
		$phone=$_GPC["phone"];
		$addr=$_GPC["addr"];
	
		$nicename=$_GPC["nicename"];
		$niceshop=$_GPC["niceshop"];
		$province=$_GPC["province"];
	    
	
		//完善用户信息
		$result=pdo_fetch("select * from ".tablename("dt_userinfo")." where openid=:openid and rid=:rid",array(":openid"=>$openid,":rid"=>$rid));
		
		$pars = array("nick"=>$nick,"headimg"=>$headimg,"name"=>$name,"phone"=>$phone,"nicename"=>$nicename,"niceshop"=>$niceshop,"province"=>$province);
		pdo_update("dt_userinfo", $pars,array("openid"=>$openid,"rid"=>$rid));
		
	
		
		$fmdata["success"]=1;
		echo json_encode($fmdata);
	}
	
	
	
	/**
	 * 添加成绩
	 */
	public function domobileaddchengji(){
		global $_W,$_GPC;
		load()->func('tpl');
		$rid=$_GPC["rid"];
		$acid=$_W['uniacid'];
		$reply=pdo_fetch("SELECT * FROM " . tablename('dt_question_reply') . " WHERE rid = :rid ", array(':rid' => $rid));
		$zongfen=intval($reply["zongfen"]);
	
		$openid = $_W["openid"];
		if($reply["subscribe"]==1){
			$nick=$_W['fans']['nickname'];
			$headimg=$_W['fans']['tag']['avatar'];
		}else{
			$userinfo=$this->getUserInfo($rid);
			$obj = json_decode($userinfo);
			$nick=$obj->nickname;
			$headimg=$obj->headimgurl;
		}
		
		
		$fromid=$_GPC["fromid"];
		//$points=intval($_GPC["totalpoints"])<=$zongfen?intval($_GPC["totalpoints"]):$zongfen;
		//答对
		if(intval($_GPC["totalpoints"])>=$zongfen){
			$points=rand($reply['zongfen1'],$zongfen);
		}else{
			$points=0;
		}
		$stime=$_COOKIE["stime"];
		$sytime=time()-intval($stime);
		$questime=$reply["questiontime"];
		if(intval($sytime)>intval($questime)*60){
			$sytime=intval($questime)*60;
		}
		$time=date('Y-m-d H:i:s',time());
		$name=$_GPC["name"];
		$phone=$_GPC["phone"];
		$addr=$_GPC["addr"];
		
		//添加成绩记录
		//是否已分享
		$addtime=date('Y-m-d',time());
		$usershare=pdo_fetch("SELECT * FROM ". tablename("dt_usershare")." WHERE openid=:openid and rid=:rid and addtime=:addtime
			 ORDER BY ID DESC LIMIT 1" , array(":openid"=>$openid,":rid"=>$rid,":addtime"=>$addtime));
		$status=$usershare ? 1 :0;
		
		$params = array("rid"=>$rid,"iacid"=>$acid, "uniacid"=>$acid,"openid"=>$openid, "nick"=>$nick,
				"headimg"=>$headimg,"points"=>$points,"sytime"=>$sytime,"sycount"=>0,"time"=>$time,
				"ljstatus"=>0,"ljtime"=>0,'status'=>$status);
		pdo_insert("dt_userpoints", $params);
		$id=pdo_insertid();
		
		//分享进入
		if(!empty($fromid)){
			$relist=pdo_fetchall("select * from ".tablename("dt_usershare")." where fromuserid=:fromid and openid=:openid and rid=:rid",array(":fromid"=>$fromid,":openid"=>$openid,":rid"=>$rid));
			//如果超过分享次数上限
			$sharelist=pdo_fetchall("select * from ".tablename("dt_usershare")." where fromuserid=:fromid and rid=:rid",array(":fromid"=>$fromid,":rid"=>$rid));
			$is_max=0;
			if($reply["maxcount"]!=0 && !empty($reply["maxcount"]) && $reply["maxcount"]<=count($sharelist)){
				$is_max=1;
			}
			if(count($relist)>0 || $is_max==1){
				//如果已经分享过，则不处理
			}else{
				//更新分享人的答题次数+1
				$userinfo = pdo_fetch("SELECT * FROM ". tablename("dt_userinfo")." WHERE openid=:openid and rid=:rid LIMIT 1" , array(":openid"=>$fromid,":rid"=>$rid));
				$shyucount=intval($userinfo["shyucount"])+1;
				$data=array("shyucount"=>$shyucount);
				$param=array("openid"=>$fromid,"rid"=>$rid);
				pdo_update("dt_userinfo",$data,$param);
			}

			//添加分享记录
			$shareparams = array("rid"=>$rid,"iacid"=>$acid, "uniacid"=>$acid,"fromuserid"=>$fromid, "openid"=>$openid,"nick"=>$nick,"headimg"=>$headimg,"addtime"=>$time);
			$sharetable='dt_usershare';
			pdo_insert($sharetable, $shareparams);
		}
		
		
		//完善用户信息
		$result=pdo_fetch("select * from ".tablename("dt_userinfo")." where openid=:openid and rid=:rid",array(":openid"=>$openid,":rid"=>$rid));
		if($reply["iswanshan"]==1 && empty($result['name'])){
			$pars = array("nick"=>$nick,"headimg"=>$headimg,"name"=>$name,"phone"=>$phone,"addr"=>$addr);
			pdo_update("dt_userinfo", $pars,array("openid"=>$openid,"rid"=>$rid));
		}
		
		//更新用户成绩
		$userinfo=pdo_fetch("select * from ".tablename("dt_userinfo")." where openid=:openid and rid=:rid",array(":openid"=>$openid,":rid"=>$rid));
		
		//if(empty($userinfo['points']) || $points>$userinfo['points'] || ($points==$userinfo['points'] && $sytime<$userinfo['sytime'])){
			//$shyucount=$userinfo['shyucount']-1;
			$updata=array(
				"points"=>$points,
				"sytime"=>$sytime,
				"pointstime"=>time()	
			//	"shyucount"=>$shyucount,
			);
			pdo_update("dt_userinfo",$updata,array("openid"=>$openid,"rid"=>$rid));
	//	}
		$fmdata["success"]=1;
		$fmdata["points"]=$points;
		echo json_encode($fmdata);
	}
}